import re

import requests
from account.ydt_account_service import YdtAccountService
from manager.lock_manager import LockManager
from model.park_spider import ParkSpider
from model.park_platform import ParkPlatform
from model.car_number import CarNumber
from model.result import Result
from model.error import ParkSpiderError, ParkSpiderErrorCode, TokenExpireError, BannedAccountError

import dateutil.parser as dateutil

from urllib import parse
import common.http as http
import spider_config
import json
from datetime import datetime
from common.logger import logger
from database.park_location_record_table import ParkLocationRecordTable
import hashlib
import json
import base64

class AirunParkSpider(ParkSpider):
    def platform(self) -> ParkPlatform:
        return ParkPlatform(spider_config.airun_park_id)

    def query(self, carNumber: CarNumber) -> Result:
        result = Result()
        result.platform = self.platform()
        result.car_number = carNumber

        account = self.getAccount()

        if not account:
            raise ParkSpiderError(ParkSpiderErrorCode.AirunAccountEmpty)
        
        with LockManager.instance().get(self.platform().id, account):
            url = f"https://wx.parkingwang.com/find_car/get_record"

            headers = {
                "Host": "wx.parkingwang.com",
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                "User-Agent": "User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 16_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.34(0x1800222a) NetType/WIFI Language/en",
                "Referer": "https://wx.parkingwang.com/",
                "Connection": "keep-alive",
                "Cookie": f"parking_ses={account}",
            }

            #vpl=base64.encode(urlencode({carNumber}))
            vpl = base64.b64encode(parse.quote(str(carNumber)).encode("utf-8")).decode("utf-8")

            rsp = http.post(
                url,
                headers=headers,
                data=f"vpl={vpl}",
                proxies=self.getProxy(),
                timeout=self.getTimeout(),
            )

        if rsp.status_code == 403:
            raise BannedAccountError(account)

        if rsp.status_code != 200:
            logger.error(f"艾润停车王请求异常:{rsp.status_code}")
            return result

        rspJson = rsp.json()

        if rspJson["code"] != 'ok':
            return result
        
        if "data" not in rspJson or "park_in_record" not in rspJson["data"]:
            logger.error(f"艾润停车王查询异常:{rspJson}")
            return result

        parkCode = rspJson["data"]["park_in_record"]["park_code"]
        result.success = True
        result.enter_time = datetime.fromtimestamp(rspJson["data"]["park_in_record"]["in_time"])

        with ParkLocationRecordTable(spider_config.airun_park_id) as db:
            record = db.query_by_code(parkCode)
            if record:
                result.park_name = record
            else:
                logger.error(f"艾润停车王未匹配到车场:{parkCode}")
                result.success = False
        return result
    
    # def query(self, carNumber: CarNumber) -> Result:
    #     result = Result()
    #     result.platform = self.platform()
    #     result.car_number = carNumber

    #     account = self.getAccount()

    #     if not account:
    #         raise ParkSpiderError(ParkSpiderErrorCode.AirunAccountEmpty)
        
    #     url = f"https://owner.irainone.com/bill/record"

    #     headers = {
    #         "Authorization": account
    #     }

    #     data  = {"vpl":str(carNumber),"park_code":0}

    #    # with LockManager.instance().get(self.platform().id, account):
    #     rsp = http.post(
    #         url,
    #         headers=headers,
    #         json=data,
    #         proxies=self.getProxy(),
    #         timeout=self.getTimeout(),
    #     )

    #     if rsp.status_code != 200:
    #         logger.error(f"艾润停车王请求异常:{rsp.status_code}")
    #         return result

    #     rspJson = rsp.json()

    #     if rspJson["code"] == 1005:
    #         raise BannedAccountError(account)

    #     if rspJson["code"] == -1:
    #         raise TokenExpireError(account)

    #     if rspJson["code"] != 0:
    #         return result
        
    #     if "data" not in rspJson:
    #         logger.error(f"艾润停车王查询异常:{rspJson}")
    #         return result

    #     parkCode = rspJson["data"]["park_code"]
    #     result.success = True
    #     result.enter_time = datetime.fromtimestamp(rspJson["data"]["in_time"])

    #     with ParkRecordTable(spider_config.airun_park_id) as db:
    #         record = db.query_by_code(parkCode)
    #         if record:
    #             result.park_name = record
    #         else:
    #             logger.error(f"艾润停车王未匹配到车场:{parkCode}")
    #     return result
